package com.ewzj.bigdata.mvp.ui.activity;

import android.animation.Animator;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.ewzj.bigdata.R;
import com.ewzj.bigdata.app.constants.AppConstants;
import com.ewzj.bigdata.di.component.DaggerArticleDetailComponent;
import com.ewzj.bigdata.di.module.ArticleDetailModule;
import com.ewzj.bigdata.mvp.contract.ArticleDetailContract;
import com.ewzj.bigdata.mvp.model.entity.ShareDataBean;
import com.ewzj.bigdata.mvp.model.entity.resbean.ArticleBean;
import com.ewzj.bigdata.mvp.model.entity.resbean.CollectBean;
import com.ewzj.bigdata.mvp.model.entity.resbean.NewBean;
import com.ewzj.bigdata.mvp.presenter.ArticleDetailPresenter;
import com.ewzj.bigdata.mvp.ui.adapter.ListCollectAdapter;
import com.ewzj.bigdata.mvp.ui.adapter.NewsAdapter;
import com.example.zhouwei.library.CustomPopWindow;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.http.imageloader.glide.ImageConfigImpl;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.utils.DeviceUtils;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zzhoujay.richtext.CacheType;
import com.zzhoujay.richtext.ImageHolder;
import com.zzhoujay.richtext.RichText;
import com.zzhoujay.richtext.callback.Callback;
import com.zzhoujay.richtext.ig.DefaultImageDownloader;
import com.zzhoujay.richtext.ig.DefaultImageGetter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class ArticleDetailActivity extends BaseActivity<ArticleDetailPresenter> implements ArticleDetailContract.View, View.OnClickListener {


    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_timeinfo)
    TextView tvTimeinfo;
    @BindView(R.id.tv_desc)
    TextView tvDesc;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.tv_collect)
    TextView tvCollect;
    @BindView(R.id.tv_font)
    TextView tvfont;
    @BindView(R.id.rl_font)
    RelativeLayout rl_font;
    @BindView(R.id.fl_img)
    FrameLayout fl_img;
    @BindView(R.id.ll_collect)
    LinearLayout llcollect;
    @BindView(R.id.rv_like)
    RecyclerView rvLike;
    @BindView(R.id.tv_collecttitle)
    TextView tvcollecttitle;
    @BindView(R.id.rv_collection)
    RecyclerView rvCollection;
    @BindView(R.id.ll_articledetail)
    LinearLayout llArticledetail;
    @BindView(R.id.videplayer)
    JZVideoPlayerStandard videplayer;
    @BindView(R.id.tv_videoname)
    TextView tvVideoname;
    @BindView(R.id.tv_videotime)
    TextView tvVideotime;
    @BindView(R.id.ll_videodetail)
    LinearLayout llVideodetail;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.tvcancelcollect)
    TextView tvcancelcollect;
    @BindView(R.id.tvdocollect)
    TextView tvdocollect;
    @BindView(R.id.toolbar)
    AutoToolbar toolbar;
    private NewBean newBean;
    private ArticleBean articleBean;
    private ListCollectAdapter listCollectAdapter;
    private CustomPopWindow fontpopWindow;

    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerArticleDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .articleDetailModule(new ArticleDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        RichText.initCacheDir(DataHelper.getCacheFile(this));
        return R.layout.activity_article_detail; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        init();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        init();
    }

    private void init() {
        newBean = getIntent().getParcelableExtra(AppConstants.EXTRA_DATA);
        if (newBean == null) {
            finish();
        }

        if (TextUtils.isEmpty(newBean.getVideo()) && newBean.getType() != 4) {
            if (newBean.getType() == 2) {
//                多图情况需要隐藏字体调节按钮
                toolbar.setVisibility(View.VISIBLE);
                rl_font.setVisibility(View.GONE);
                fl_img.setVisibility(View.GONE);
            } else {
                toolbar.setVisibility(View.GONE);
            }
            llArticledetail.setVisibility(View.VISIBLE);
            llVideodetail.setVisibility(View.GONE);
            tvTitle.setText(newBean.getTitle());
            tvTimeinfo.setText(newBean.getTime());
            mPresenter.loadArticleInfo(newBean.getId() + "");
            mPresenter.loadGuessLike(newBean.getId() + "", newBean.getCategory_id() + "");
        } else {
//                视频情况需要隐藏字体调节按钮
            toolbar.setVisibility(View.GONE);
            rl_font.setVisibility(View.GONE);
            llArticledetail.setVisibility(View.GONE);
            llVideodetail.setVisibility(View.VISIBLE);
            tvVideoname.setText(newBean.getTitle());
            tvVideotime.setText(newBean.getTime());
            mPresenter.loadArticleInfo(newBean.getId() + "");
            mPresenter.loadGuessLike(newBean.getId() + "", newBean.getCategory_id() + "");
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void showArticleView(ArticleBean articleBean) {
        this.articleBean = articleBean;
        ImageLoader imageLoader = ArmsUtils.obtainAppComponentFromContext(this).imageLoader();
        if (articleBean.getThumb().size() > 0 && articleBean.getThumb() != null && !TextUtils.isEmpty(articleBean.getThumb().get(0))) {
            imageLoader.loadImage(this, ImageConfigImpl.builder().imageView(ivImg)
                    .url(articleBean.getThumb().get(0)).transformation(new CenterCrop()).build());
        } else {
            ivImg.setVisibility(View.GONE);
        }
        tvTimeinfo.setText("发布于" + articleBean.getTime());
        tvDesc.setText(articleBean.getSummary());
//        if (articleBean.isIs_collect()) {
//            DrawableProvider.setLeftDrawable(tvCollect, this.getDrawable(R.drawable.icon_collection_s));
//        } else {
//            DrawableProvider.setLeftDrawable(tvCollect, this.getDrawable(R.drawable.icon_collection_n));
//        }
        tvTitle.setText(articleBean.getTitle());
        tvVideotime.setText("发布于" + articleBean.getTime());
        tvVideoname.setText(articleBean.getTitle());
        RichText.from(articleBean.getContent())
                .showBorder(false)
                .scaleType(ImageHolder.ScaleType.center)
                .cache(CacheType.all)
                .bind(articleBean)
                .imageGetter(new DefaultImageGetter())
                .imageDownloader(new DefaultImageDownloader())
                .done(new Callback() {
                    @Override
                    public void done(boolean imageLoadDone) {

                    }
                }).into(tvContent);
        tvContent.setText(articleBean.getContent());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RichText.clear(this);
        RichText.recycle();
    }

    //    猜你喜欢
    @Override
    public void showGuessLikeRv(List<NewBean> resNewsData) {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        rvLike.setLayoutManager(linearLayoutManager);
        NewsAdapter newsAdapter = new NewsAdapter(resNewsData);
        rvLike.setAdapter(newsAdapter);
    }


    void startCommentActivity() {
        Intent intent = new Intent(this, CommentListActivity.class);
        intent.putExtra(AppConstants.EXTRA_DATA, articleBean);
        ArmsUtils.startActivity(intent);
    }


    @OnClick({R.id.iv_back, R.id.iv_wechat, R.id.iv_sina, R.id.iv_qq, R.id.tv_font, R.id.tv_collect,
            R.id.tv_comment, R.id.tv_share, R.id.tvdocollect, R.id.tvcancelcollect})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                killMyself();
                break;
            case R.id.iv_wechat:
                mPresenter.ShareWeb(newBeanToSharedata(newBean), SHARE_MEDIA.WEIXIN);
                break;
            case R.id.iv_sina:
                mPresenter.ShareWeb(newBeanToSharedata(newBean), SHARE_MEDIA.SINA);
                break;
            case R.id.iv_qq:
                mPresenter.ShareWeb(newBeanToSharedata(newBean), SHARE_MEDIA.QQ);
                break;
            case R.id.tv_font:
                showFontSizeSeletor();
                break;
            case R.id.tv_collect:
                mPresenter.loadCollectData();
                break;
            case R.id.tv_comment:
                startCommentActivity();
                break;
            case R.id.tv_share:
                break;
            case R.id.tvdocollect:
                if (listCollectAdapter.getSelectItem() == null) {
                    ArmsUtils.snackbarText("请选择你要收藏的分组");
                    return;
                }
                hideDoCollectView();
                mPresenter.doCollect(newBean.getId() + "", listCollectAdapter.getSelectItem().getId() + "");
                break;
            case R.id.tvcancelcollect:
                hideDoCollectView();
                break;
        }
    }

    void showFontSizeSeletor() {
        int width = (int) DeviceUtils.dpToPixel(this, 70);
        int height = (int) DeviceUtils.dpToPixel(this, 117);
        View view = View.inflate(this, R.layout.font_choice, null);
        view.findViewById(R.id.tv_samll).setOnClickListener(this);
        view.findViewById(R.id.tv_middle).setOnClickListener(this);
        view.findViewById(R.id.tv_big).setOnClickListener(this);
        fontpopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(view)//显示的布局
                .size(width, height)
                .setFocusable(true)
                .create();//创建PopupWindow;
        fontpopWindow.showAsDropDown(rl_font, (rl_font.getWidth() - fontpopWindow.getWidth()) / 2, -(rl_font.getHeight() + fontpopWindow.getHeight()));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_samll:
                setFontSize(12f);
                fontpopWindow.dissmiss();
                break;
            case R.id.tv_middle:
                setFontSize(14f);
                fontpopWindow.dissmiss();
                break;
            case R.id.tv_big:
                setFontSize(16f);
                fontpopWindow.dissmiss();
                break;
        }
    }

    /**
     * @param fontSize
     */
    private void setFontSize(float fontSize) {
        tvContent.setTextSize(fontSize);
        tvContent.postInvalidate();
    }

    @Override
    public void showDoCollectPopWindow(List<CollectBean> collectBeans, Boolean isloadmore) {
        llcollect.setVisibility(View.VISIBLE);
        YoYo.with(Techniques.FadeInUp)
                .duration(500)
                .repeat(0)
                .playOn(llcollect);
        tvcollecttitle.setText(newBean.getTitle());
        if (listCollectAdapter == null) {
            listCollectAdapter = new ListCollectAdapter(collectBeans);
        }
        rvCollection.setLayoutManager(new LinearLayoutManager(this));
        rvCollection.setAdapter(listCollectAdapter);
        listCollectAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPresenter.loadMoreCollectData();
            }
        }, rvCollection);
        listCollectAdapter.disableLoadMoreIfNotFullPage();
        if (isloadmore && listCollectAdapter != null) {
            listCollectAdapter.addData(collectBeans);
        } else {
            listCollectAdapter.setNewData(collectBeans);
        }

    }

    @Override
    public ListCollectAdapter obtainAdapter() {
        if (listCollectAdapter == null) {
            listCollectAdapter = new ListCollectAdapter(new ArrayList<>());
        }
        return listCollectAdapter;
    }

    private ShareDataBean newBeanToSharedata(NewBean newBean) {
        ShareDataBean shareDataBean = new ShareDataBean();
        shareDataBean.setTitle(newBean.getTitle());
        return shareDataBean;
    }

    private void hideDoCollectView() {
        YoYo.with(Techniques.FadeOutDown)
                .duration(500)
                .repeat(0)
                .withListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        llcollect.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                })
                .playOn(llcollect);
    }

    @Override
    public void onBackPressed() {
        if (llcollect.getVisibility() == View.VISIBLE) {
            hideDoCollectView();
        } else {
            super.onBackPressed();
        }

    }

    @Override
    public void notifyCollectDataChange(List<CollectBean> collectBeans) {
        if (listCollectAdapter != null) {
            listCollectAdapter.addData(collectBeans);
        }
    }

    @Override
    public void showVideoView(ArticleBean newBean) {
        if (!TextUtils.isEmpty(newBean.getVideo())) {
            videplayer.setUp(newBean.getVideo(), JZVideoPlayer.SCREEN_WINDOW_NORMAL, newBean.getTitle());
            ArmsUtils.obtainAppComponentFromContext(this).imageLoader()
                    .loadImage(this, ImageConfigImpl
                            .builder()
                            .url(newBean.getThumb().get(0))
                            .imageView(videplayer.thumbImageView)
                            .build());
        }
        tvVideoname.setText(newBean.getTitle());
        tvVideotime.setText("发布于" + newBean.getTime());
    }

    @Override
    public void refreshVideo(NewBean newBean) {

    }
}
